﻿using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using Communication.Bootstrap;
using Communication.Channel;
using Communication.Channel.Serial;
using Communication.Message;
using Communication.Message.Osc;
using Frame.Utility.Handler;
using Growatt.Component.Frm;
using Growatt.DuiHelpers;
using Growatt.OSC.Util;
using Growatt.WaveData;
using Growatt.WaveData.DataSetResolve;
using Growatt.WaveData.VirtualOscilloscope;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Oscilloscope.Adjust;
using Oscilloscope.ChannelBuffer;
using Oscilloscope.Screen;
using Oscilloscope.Util;
using Sunny.UI;
using Sunny.UI.Win32;
using Vosc.Coff;
using Vosc.Logging;
using Vosc.VirtualOscilloscope;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;

namespace Vosc
{
    // Token: 0x02000018 RID: 24
    public partial class MainForm : Form
    {
        public MainForm()
        {

            //// 创建并显示自定义对话框
            //FrmInputBox2 dialog = new FrmInputBox2();
            //DialogResult result = dialog.ShowDialog();
            //// 处理对话框返回的结果
            //if (result == DialogResult.OK)
            LoadConfigSelcectedItems();
            LoadConfigSys();//导入波特率
            Program.CountChannel = int.Parse("4");
            tempFrameData = new short?[Program.CountChannel];
            LoadConfig("ConfigSys.ini");

            this.InitializeComponent();

            this.FormClosed += (s, e) =>
            {
                CloseToSaving();
            };
            // 在初始化代码中启动处理线程（比如构造函数）
            _processingThread = new Thread(ProcessQueue);
            _processingThread.IsBackground = true;
            _processingThread.Start();
            //  DwarfHelper.DwarfHelperInstance.LoadFile();
            this.runState = MainForm.RunState.Stoped;

            // 创建图标对象
            if (File.Exists(OscilloscopeControl.ModelAppSettingsCustom.OutPathHistory))
            {
                toolStripLabel2.Text = " 当前加载文件为:" + OscilloscopeControl.ModelAppSettingsCustom.OutPathHistory;
            }
            else
            {
                toolStripLabel2.Text = "文件为:" + OscilloscopeControl.ModelAppSettingsCustom.OutPathHistory + " 不存在,请检查路径是否正确!";
                toolStripLabel2.ForeColor = Color.Red;
            }
            Icon icon = Icon.FromHandle(LEDVANCE.Oscilloscope.Properties.Resources.LOGO2.GetHicon());
            this.Icon = icon;
            //this.WindowState = FormWindowState.Maximized;
            DisConnectStopSample += (o) => { StopSample(); };
            ChannelWriters += (_ctlMsg) =>
            {
                if (this.runState == MainForm.RunState.Started)
                {
                    MessageBox.Show("请先停止!");
                    return false;
                }

                this.runState = MainForm.RunState.Stoped;
                try
                {
                    createChanelHelper();
                    MainForm.getChannelHelper.Invoke(channel);
                    channel.WriteAsync(_ctlMsg);
                    return true;
                }
                catch (Exception exception3)
                {
                    this.channel.Close();
                    while (!this.channel.IsClosed())
                    {
                        Thread.Sleep(500);
                    }

                    if (this.swOfSaveFile != null)
                    {
                        this.swOfSaveFile.Close();
                        this.swOfSaveFile.Dispose();
                        this.swOfSaveFile = null;
                    }
                    if (this.chMemoryBufs != null)
                    {
                        this.chMemoryBufs.Clear();
                        this.chMemoryBufs = null;
                    }
                    this.preFrameNo = null;
                    this.receivedFrameCount = 0UL;
                    this.paddingFrameCount = 0UL;
                    return false;
                }
                return true;
            };
            this.SizeChanged += _Resize;
            this.oscilloscopeControl1.AllowDrop = true;
            this.AllowDrop = true;
            this.WindowState = OscilloscopeControl.ModelAppSettingsCustom.ModeWindow;
            // 确保其他初始化代码存在
            OscilloscopeScreen.ShowPath += async (path) =>
            {
                try
                {
                    await ShowPath(path);
                }
                catch (global::System.Exception)
                {
                }
            };
            oscilloscopeControl1.DragEnter += new System.Windows.Forms.DragEventHandler(this.oscilloscopeControl1_DragEnter);
            oscilloscopeControl1.DragDrop += new System.Windows.Forms.DragEventHandler(this.oscilloscopeControl1_DragDrop);
        }


        public static Func<bool> GetConfigChanneel;

        // 队列处理线程方法
        private void ProcessQueue()
        {
            while (!_cts.IsCancellationRequested)
            {
                if (_audioQueue.TryDequeue(out List<short[]> frames))
                {
                    ProcessFrame(frames);
                }
                else
                {
                    Thread.Sleep(100);
                }
            }
        }

        // 示例帧处理方法
        private void ProcessFrame(List<short[]> frames)
        {
            DataReceived(frames);
        }

        // 窗体关闭时停止线程
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            _cts.Cancel();
            _processingThread?.Join(1000); // 等待线程结束
            base.OnFormClosing(e);
        }

        private void _Resize(object sender, EventArgs e)
        {
            // 获取窗体的新大小
            Size newSize = this.Size;
            int width = newSize.Width;
            int height = newSize.Height;
            //Console.WriteLine($"窗体的新大小: 宽度 = {width}, 高度 = {height}");
            if (this.WindowState == FormWindowState.Maximized)
            {
                // 窗口被最大化时执行的代码
                //Console.WriteLine("窗口被最大化");

            }
            else if (this.WindowState == FormWindowState.Minimized)
            {
                // 窗口被最小化时执行的代码
                //Console.WriteLine("窗口被最小化");
            }
            else if (this.WindowState == FormWindowState.Normal)
            {
                // 窗口恢复到正常大小时执行的代码
                //Console.WriteLine("窗口恢复正常大小");
            }
            OscilloscopeControl.ModelAppSettingsCustom.ModeWindow = this.WindowState;

        }
        private static void LoadConfig(string name)
        {
            if (File.Exists(Path.Combine($"{Environment.CurrentDirectory}\\Parser", name))) //將保存內容顯示在界面中
            {
                string file = File.ReadAllText(Path.Combine($"{Environment.CurrentDirectory}\\Parser", name));
                ////反序列化
                var list = DuiJsonHelper.JsonToObject<List<ModelSaveString>>(file);
                if (list != null)
                    OscilloscopeControl.modelSaveStrings = list;
                else OscilloscopeControl.modelSaveStrings = new List<ModelSaveString>(); ;
            }
        }
        private static void LoadConfigSelcectedItems(string Name = "ModelSaveChaneltempLoad.ini")
        {
            if (File.Exists(Path.Combine($"{Environment.CurrentDirectory}\\Parser", Name))) //將保存內容顯示在界面中
            {
                string fileDatas = File.ReadAllText(Path.Combine($"{Environment.CurrentDirectory}\\Parser", Name));
                OscilloscopeControl.ModelSaveChanelLoadsFiles = DuiJsonHelper.JsonToObject<ModelSaveChaneltempLoad>(fileDatas);
            }
        }
        private static void LoadConfigSys(string Name = "sys.ini")
        {
            if (File.Exists(Path.Combine($"{Environment.CurrentDirectory}\\Parser", Name))) //將保存內容顯示在界面中
            {
                string fileDatas = File.ReadAllText(Path.Combine($"{Environment.CurrentDirectory}\\Parser", Name));
                OscilloscopeControl.ModelAppSettingsCustom = DuiJsonHelper.JsonToObject<AppSettingsCustom>(fileDatas);
            }
        }
        public static int LoadConfig_ChannelCount(string name)
        {
            try
            {
                if (File.Exists(Path.Combine($"{Environment.CurrentDirectory}\\Parser", name))) //將保存內容顯示在界面中
                {
                    string file = File.ReadAllText(Path.Combine($"{Environment.CurrentDirectory}\\Parser", name));
                    ////反序列化
                    var list = DuiJsonHelper.JsonToObject<ModelSaveChanelCount>(file);
                    if (list != null)
                    {
                        OscilloscopeControl.modelSaveChanelCount = list;

                        return OscilloscopeControl.modelSaveChanelCount.ChanelCount;
                    }
                }

            }
            catch (Exception ex)
            {
                return 7; //默认返回7个
            }
            return 7; //默认返回7个
        }

        private static void CloseToSaving()
        {
            try
            {
                var JsonString = DuiJsonHelper.ObjectToJson(OscilloscopeControl.modelSaveStrings);
                if (JsonString != null)
                {
                    var re = DuiHelperFile.SaveFile(JsonString, Path.Combine($"{Environment.CurrentDirectory}\\Parser", $"ConfigSys.ini"));//由于Ttxt文件会加密
                    //Console.WriteLine("保存成功!");
                }
                int index = -1;
                OscilloscopeControl.ModelSaveChanelLoadsFiles?.ListModelSaveString.Clear();
                var listTemp = OscilloscopeControl.listChnnel.Select((k) =>
                {
                    index++;
                    var ctrl = OscilloscopeControl.userControl1s[index].cuurentSelectItem;
                    var item = OscilloscopeControl.modelSaveStrings.FirstOrDefault(o => ctrl!=null&& o.Name.Equals(ctrl.Name) &&
                      o.Type.Equals(ctrl.Type) &&
                      o.Scale.Equals(ctrl.Scale)
                      );
                    OscilloscopeControl.ModelSaveChanelLoadsFiles.ListModelSaveString.Add(item);
                    return k;
                }).ToArray();

                //
                var JsonString_ModelSaveChanelLoadFile = DuiJsonHelper.ObjectToJson(OscilloscopeControl.ModelSaveChanelLoadsFiles);
                if (JsonString_ModelSaveChanelLoadFile != null)
                {
                    var re = DuiHelperFile.SaveFile(JsonString_ModelSaveChanelLoadFile, Path.Combine($"{Environment.CurrentDirectory}\\Parser", $"ModelSaveChaneltempLoad.ini"));//由于Ttxt文件会加密
                };

                var JsonString_AppSettingsCustom = DuiJsonHelper.ObjectToJson(OscilloscopeControl.ModelAppSettingsCustom);
                if (JsonString_AppSettingsCustom != null)
                {
                    var re = DuiHelperFile.SaveFile(JsonString_AppSettingsCustom, Path.Combine($"{Environment.CurrentDirectory}\\Parser", $"sys.ini"));//保存波特率
                };

                var JsonString_modelSaveChanelCount = DuiJsonHelper.ObjectToJson(OscilloscopeControl.modelSaveChanelCount);
                if (JsonString_modelSaveChanelCount != null)
                {
                    var re = DuiHelperFile.SaveFile(JsonString_modelSaveChanelCount, Path.Combine($"{Environment.CurrentDirectory}\\Parser", $"ConfigSaveChanelCount.ini"));//由于Ttxt文件会加密
                };




                if (OscilloscopeControl.listChnnel.Count > 0)
                {

                    var list = OscilloscopeControl.listChnnel.Select((k) =>
                    {
                        return new ConfigChannelControlModel(k.channelSN, k.lineColor, k.lineWidth, k.signalName, k.valuePerCellGrade, k.verPos, k.bitMask);
                    });
                    var JsonStringConfigChannelControlModel = DuiJsonHelper.ObjectToJson(list.ToList());
                    var re2 = DuiHelperFile.SaveFile(JsonStringConfigChannelControlModel, Path.Combine($"{Environment.CurrentDirectory}\\Parser", $"ConfigChanelControlSys.ini"));//由于Ttxt文件会加密
                }
            }
            catch (Exception exp)
            {
                DuiHelperLog.WriteErrorLog(exp);
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                if (Directory.Exists(SystemSetting.INTERNAL_DATA_DIR))
                {
                    Directory.Delete(SystemSetting.INTERNAL_DATA_DIR, true);
                }
                ActionShowConnect += (s) =>
                {
                    toolStripLabel_output.ForeColor = Color.Blue;
                    toolStripLabel_output.Text = s;
                };
                OscilloscopeControl.ShowData += (s) =>
                {
                    toolStripLabel1.ForeColor = Color.Blue;
                    toolStripLabel1.Text = s;
                };


            }
            catch (Exception ex)
            {

                DuiHelperLog.WriteErrorLog(ex);
            }
        }

        private void LoadTestDataMenuItem_Click(object sender, EventArgs e)
        {
            this.oscilloscopeControl1.ClearChannelBuffer();
            Dictionary<int, IChannelBuffer> dictionary = new Dictionary<int, IChannelBuffer>();
            string text = Application.StartupPath + "\\testdata";
            if (!Directory.Exists(text))
            {
                Directory.CreateDirectory(text);
            }
            for (int i = 0; i < Program.CountChannel; i++)
            {
                string text2 = text + "\\data" + (i + 1).ToString();
                if (File.Exists(text2))
                {
                    File.Delete(text2);
                }
                if (i % 4 == 0)
                {
                    TestDataGenerator.GenerateSingleDigitalCurve(text2, 50, 4000, 30);
                    IChannelBuffer value = ChannelBufferFactory.FileChannelBuffer(text2);
                    dictionary.Add(i + 1, value);
                }
                else if (i % 4 == 1)
                {
                    TestDataGenerator.GenerateMultipleDigitalCurve(text2, 50, 4000, 30);
                    IChannelBuffer value2 = ChannelBufferFactory.FileChannelBuffer(text2);
                    dictionary.Add(i + 1, value2);
                }
                else
                {
                    TestDataGenerator.GenerateSineCurve(text2, 50, 4000, (double)i * 3.1415926535897931, 220.0, 30);
                    IChannelBuffer value3 = ChannelBufferFactory.FileChannelBuffer(text2);
                    dictionary.Add(i + 1, value3);
                }
            }
            this.oscilloscopeControl1.SetChannelBuffer(dictionary);
            this.oscilloscopeControl1.SetWindowCenterTime(0.0);
        }


        public VirtualOscilloscope.OscilloscopeControl GETcONTROIL()
        {
            return oscilloscopeControl1;
        }

        private void toolStripButtonChSel_Click(object sender, EventArgs e)
        {
            if (toolStripButtonLoadDataFromDSP.Enabled == false)
            {
                MessageBox.Show("请先点击停止");
                return;
            }
            var result = false;
            if (MainForm.GetConfigChanneel != null)
            {
                result = MainForm.GetConfigChanneel.Invoke();
                if (result)
                {
                    ConnectInitial();
                    this.StartSample();

                }
                else
                {
                    MessageBox.Show("请检查通道是否配置正确！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
        }

        private void ConnectInitial()
        {
            if (this.runState == MainForm.RunState.Started)
            {
                return;
            }
            if (!SystemSetting.IsSettingValid()) //设置所有参数是否已经连接
            {
                MessageBox.Show("设置不正确，请先进行设置！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            this.chMemoryBufs = new List<MainForm.ChannelBufferMemory>();
            Dictionary<int, IChannelBuffer> dictionary = new Dictionary<int, IChannelBuffer>();
            for (int i = 1; i < Program.CountChannel + 1; i++)
            {
                dictionary.Add(i, ChannelBufferFactory.EmptyChannelBuffer());
            }
            for (int j = 1; j < Program.CountChannel + 1; j++)
            {
                ChannelSeting channelSeting = SystemSetting.Channels[j];
                if (channelSeting.Address != null && channelSeting.Address.Value != null && channelSeting.Address.Value != 0)
                {
                    Debug.WriteLine("开始连接通道：" + $"{j}" + channelSeting.Address.Value.ToString("X8"));
                    SignalType signalType;
                    SignalRatio signalRatio = SignalRatio.x1;
                    ENUM_Ratio signalRatio1 = SystemSetting.Channels[j].WaveRatio;
                    switch (signalRatio1)
                    {
                        case ENUM_Ratio.x1:
                            signalRatio = SignalRatio.x1;
                            break;
                        case ENUM_Ratio.x10:
                            signalRatio = SignalRatio.x10;
                            break;
                        case ENUM_Ratio.x100:
                            signalRatio = SignalRatio.x100;
                            break;
                        case ENUM_Ratio.x1k:
                            signalRatio = SignalRatio.x1k;
                            break;
                        case ENUM_Ratio.x10k:
                            signalRatio = SignalRatio.x10k;
                            break;
                        case ENUM_Ratio.x100k:
                            signalRatio = SignalRatio.x100k;
                            break;
                        default:
                            break;
                    }
                    //切换有无符号
                    signalType = SignalType.AnalogSigned;
                    if (SystemSetting.Channels[j].SignalType == ENUM_001.I16)
                    {
                        signalType = SignalType.AnalogSigned;
                    }
                    else if (SystemSetting.Channels[j].SignalType == ENUM_001.U16)
                    {
                        signalType = SignalType.AnalogUnsigned;
                    }
                    else if (SystemSetting.Channels[j].SignalType == ENUM_001.MultiBit)
                    {
                        signalType = SignalType.DigitalMultiple;
                    }
                    else if (SystemSetting.Channels[j].SignalType == ENUM_001.SingleBit)
                    {
                        signalType = SignalType.DigitalSingle;
                    }
                    //往每个Chanel填充数据
                    IChannelBuffer channelBuffer = ChannelBufferFactory.MemoryChannelBuffer(SystemSetting.SampleFrenquency.Value, 30.0, signalType, signalRatio);
                    dictionary[j] = channelBuffer;
                    this.chMemoryBufs.Add(new MainForm.ChannelBufferMemory(j, channelBuffer));
                }
            }
            this.oscilloscopeControl1.SetChannelBuffer(dictionary);
            this.oscilloscopeControl1.SetWindowCenterTime(30.0 - TimePerCellAdjustGrade.Instance.GetValueOfGrade(this.oscilloscopeControl1.TimeLengthPerCellGrade) * 5.0);
            this.createChanelHelper();
        }

        static List<ENUM_Ratio> eNUM_Ratios = new List<ENUM_Ratio>();
        private void toolStripButtonLoadDataFromFile_Click(object sender, EventArgs e)
        {
            if (this.runState == MainForm.RunState.Started)
            {
                return;
            }
            eNUM_Ratios.Clear();
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.DefaultExt = "csv";
            openFileDialog.CheckPathExists = true;
            openFileDialog.Filter = "CSV Files(*.csv)|*.csv";
            openFileDialog.SupportMultiDottedExtensions = false;
            openFileDialog.ValidateNames = true;
            openFileDialog.Multiselect = false;
            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            DspDataSaveFileDataLoader dspDataSaveFileDataLoader = new DspDataSaveFileDataLoader(openFileDialog.FileName);
            DspDataSaveFileStruct fileStruct = dspDataSaveFileDataLoader.GetFileStruct();
            if (fileStruct == null)
            {
                MessageBox.Show("文件加载错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            MessageBox.Show(fileStruct.ToString(), "文件信息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            Dictionary<int, IChannelBuffer> dictionary = null;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                List<int> list = new List<int>();
                for (int i = 0; i < fileStruct.Signals.Count; i++)
                {
                    list.Add(i);
                }
                List<ChannelBufferFile> list2 = dspDataSaveFileDataLoader.Load(list.ToArray());
                if (list2 == null || list2.Count == 0)
                {
                    MessageBox.Show("文件加载错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    return;
                }
                dictionary = new Dictionary<int, IChannelBuffer>();
                for (int j = 1; j < Program.CountChannel + 1; j++)
                {
                    dictionary.Add(j, ChannelBufferFactory.EmptyChannelBuffer());
                }
                int count = 0;
                foreach (ChannelBufferFile channelBufferFile in list2)
                {
                    if (dictionary.ContainsKey(channelBufferFile.ChSN))
                    {
                        dictionary[channelBufferFile.ChSN] = ChannelBufferFactory.FileChannelBuffer(channelBufferFile.Filepath, fileStruct.Signals[count].Type.ToString() + "$" + list2[count].DecimalCount);
                    }
                    count++;
                }
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
            this.oscilloscopeControl1.SetChannelBuffer(dictionary);
            this.oscilloscopeControl1.SetWindowCenterTime(0.0);
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (this.runState == MainForm.RunState.Started)
            {
                e.Cancel = true;
                return;
            }
            base.OnClosing(e);
            this.oscilloscopeControl1.ClearChannelBuffer();
            Application.Exit();
        }

        public static Action<string> ActionShowConnect = null;
        public static Action<string> DisConnectStopSample = null;
        public static Func<OscChannelMessage, bool> ChannelWriters = null;



        private void ToolStripMenuItemAbout_Click(object sender, EventArgs e)
        {
            new AboutBox
            {
                StartPosition = FormStartPosition.CenterParent
            }.ShowDialog();
        }


        public static Action<Channel> getChannelHelper = null;
        private void toolStripButtonStopRefresh_Click(object sender, EventArgs e)
        {

            toolStripButtonLoadDataFromDSP.Enabled = true;
            this.StopSample();
            toolStripLabel_SatusSend.Text = "已停止读取";
            toolStripLabel_SatusSend.ForeColor = Color.Red;
        }
        public Channel createChanelHelper()
        {

            oscilloscopeControl1.dspDataLoadForm.SetCommParam();
            oscilloscopeControl1.dspDataLoadForm.SetSampleRate();
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            dictionary.Add("baudRate", SystemSetting.BaudRate.Value);
            dictionary.Add("dataBits", 8);
            dictionary.Add("stopBits", StopBits.One);
            dictionary.Add("parity", Parity.None);
            dictionary.Add("readTimeoutMillis", 100);
            dictionary.Add("writeTimeoutMillis", 100);
            dictionary.Add("readBufferSize", 16384);
            dictionary.Add("writeBufferSize", 1024);
            SerialAddress remoteAddress = new SerialAddress(SystemSetting.PortName);
            SerialChannelFactory channelFactory = new SerialChannelFactory();
            ClientBootstrap clientBootstrap = new ClientBootstrap(channelFactory);
            clientBootstrap.SetOptions(dictionary);
            try
            {
                //开启串口(实现配置)
                this.channel = clientBootstrap.connect(remoteAddress);
                return channel;
            }
            catch (Exception exception)
            {
                InternalLoggerFactory.Logger.Error("未能取得一个有效通信通道", exception);
                MessageBox.Show("未能取得一个有效通信通道，通信故障, 请切换串口！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return null;
            }
        }

        /// <summary>
        /// 启动
        /// </summary>
        public void StartSample()
        {
            int num = 0;
            List<int> adds = new List<int>();
            for (int i = 1; i < Program.CountChannel + 1; i++)
            {

                if (SystemSetting.Channels[i] != null && SystemSetting.Channels[i].Address != null && SystemSetting.Channels[i].Address.Value != 0)
                {
                    num++;
                }
                if (SystemSetting.Channels[i].Address != null)
                    adds.Add(SystemSetting.Channels[i].Address.Value);
            }
            var st = SystemSetting.Channels.Select(o =>
            {
                int re = 0;
                var ty = o.Value.SignalType;
                switch (ty)
                {
                    case ENUM_001.U16:
                        re = 0;
                        break;
                    case ENUM_001.I16:
                        re = 0;
                        break;
                    case ENUM_001.F32:
                        re = 1;
                        break;
                    default:
                        break;
                }
                return re;
            }).Select(o => o.ToString()).Reverse();
            var dataTypebyte = Convert.ToByte(string.Join("", st), 2); //获取所有的数据类型

            var wave1 = InternalUtils.ConvertGetByte((byte)SystemSetting.Channels[3].WaveRatio, (byte)SystemSetting.Channels[4].WaveRatio);
            var wave2 = InternalUtils.ConvertGetByte((byte)SystemSetting.Channels[1].WaveRatio, (byte)SystemSetting.Channels[2].WaveRatio);
            AddrSetChannelMessage addrSetChannelMessage = new AddrSetChannelMessage(adds.ToArray(), SystemSetting.ScopeMode, dataTypebyte, wave1, wave2);//发送所有地址信息(地址设置)
                                                                                                                                                         // AddrSetChannelMessageOrginal addrSetChannelMessage = new AddrSetChannelMessageOrginal(adds.Select(o=>(short)o).ToArray());//发送所有地址信息(地址设置)
            addrSetChannelMessage.SetSendTimeoutMillis(1000);
            addrSetChannelMessage.SetSpaceReceiveTimeoutMillis(1000);
            addrSetChannelMessage.SetTotalReceiveTimeoutMillis(1000);
            try
            {
                if (this.channel != null)
                {
                    this.channel.WriteAsync(addrSetChannelMessage);
                    addrSetChannelMessage.AwaitUninterruptibly();
                    if (!addrSetChannelMessage.IsSuccess())
                    {

                        throw new Exception("地址设置消息处理失败", addrSetChannelMessage.GetCause());
                    }
                    if (addrSetChannelMessage.ErrorCode != OscErrorCode.SUCCESS)
                    {
                        MessageBox.Show("地址设置消息处理失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);

                        throw new Exception("地址设置消息处理失败", new Exception("消息错误码不是 SUCCESS"));
                    }
                    toolStripLabel_SatusSend.Text = "正在读取中";
                    toolStripLabel_SatusSend.ForeColor = Color.Blue;
                    toolStripButtonLoadDataFromDSP.Enabled = false;
                }
                else
                {
                    MessageBox.Show("地址设置消息处理失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }

            }
            catch (Exception exception2)
            {
                this.channel.Close();
                while (!this.channel.IsClosed())
                {
                    Thread.Sleep(500);
                }
                InternalLoggerFactory.Logger.Error(string.Format("write data [fun={0} errorcode={1}] error, sendmsg:{2}, receivemsg:{3}", new object[]
                {
                    addrSetChannelMessage.Fun,
                    addrSetChannelMessage.ErrorCode.ToString(),
                    addrSetChannelMessage.HexDumpSendMessage(),
                    addrSetChannelMessage.HexDumpReceiveMessage()
                }), exception2);
                MessageBox.Show("设置通道地址错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            this.ctlMsg = null;
            try
            {
                if (this.channel != null)
                {
                    this.ctlMsg = new ControlChannelMessage(num);
                    this.ctlMsg.SetSendTimeoutMillis(1000);
                    this.ctlMsg.SetSpaceReceiveTimeoutMillis(1000);
                    this.ctlMsg.SetTotalReceiveTimeoutMillis(int.MaxValue);
                    this.ctlMsg.OnCompleted += this.Msg_OnCompleted;
                    this.ctlMsg.DataReceived += this.Msg_DataReceived;
                    if (this.swOfSaveFile != null)
                    {
                        this.swOfSaveFile.Close();
                        this.swOfSaveFile.Dispose();
                        this.swOfSaveFile = null;
                    }
                    this.hasWrittenPointCountToFile = -1;
                    this.channel.WriteAsync(this.ctlMsg);
                    this.runState = MainForm.RunState.Started;
                    this.oscilloscopeControl1.StartRefresh();
                    this.toolStripStatusLabel.Text = string.Empty;

                }
                else
                {
                    MessageBox.Show("串口占用,請切換串口！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }

            }
            catch (Exception exception3)
            {
                this.channel.Close();
                while (!this.channel.IsClosed())
                {
                    Thread.Sleep(500);
                }
                this.ctlMsg.OnCompleted -= this.Msg_OnCompleted;
                this.ctlMsg.DataReceived -= this.Msg_DataReceived;
                this.ctlMsg = null;
                if (this.swOfSaveFile != null)
                {
                    this.swOfSaveFile.Close();
                    this.swOfSaveFile.Dispose();
                    this.swOfSaveFile = null;
                }
                if (this.chMemoryBufs != null)
                {
                    this.chMemoryBufs.Clear();
                    this.chMemoryBufs = null;
                }
                this.preFrameNo = null;
                this.receivedFrameCount = 0UL;
                this.paddingFrameCount = 0UL;
                InternalLoggerFactory.Logger.Error(string.Format("write data [fun={0} errorcode={1}] error, sendmsg:{2}, receivemsg:{3}", new object[]
                {
                    this.ctlMsg.Fun,
                    this.ctlMsg.ErrorCode.ToString(),
                    this.ctlMsg.HexDumpSendMessage(),
                    this.ctlMsg.HexDumpReceiveMessage()
                }), exception3);
                MessageBox.Show("启动失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        /// <summary>
        /// 启动
        /// </summary>
        public void StartSample22(ControlChannelMessage addrSetChannelMessage)
        {
            this.ctlMsg = null;
            try
            {
                if (this.channel != null)
                {
                    this.ctlMsg = addrSetChannelMessage;


                }
                else
                {
                    MessageBox.Show("串口占用,請切換串口！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
            catch (Exception exception3)
            {
                this.channel.Close();
                while (!this.channel.IsClosed())
                {
                    Thread.Sleep(500);
                }
                this.ctlMsg.OnCompleted -= this.Msg_OnCompleted;
                this.ctlMsg.DataReceived -= this.Msg_DataReceived;
                if (this.swOfSaveFile != null)
                {
                    this.swOfSaveFile.Close();
                    this.swOfSaveFile.Dispose();
                    this.swOfSaveFile = null;
                }
                if (this.chMemoryBufs != null)
                {
                    this.chMemoryBufs.Clear();
                    this.chMemoryBufs = null;
                }
                this.preFrameNo = null;
                this.receivedFrameCount = 0UL;
                this.paddingFrameCount = 0UL;
                InternalLoggerFactory.Logger.Error(string.Format("write data [fun={0} errorcode={1}] error, sendmsg:{2}, receivemsg:{3}", new object[]
                {
                    this.ctlMsg.Fun,
                    this.ctlMsg.ErrorCode.ToString(),
                    this.ctlMsg.HexDumpSendMessage(),
                    this.ctlMsg.HexDumpReceiveMessage()
                }), exception3);
                MessageBox.Show("写入失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        /// <summary>
        /// 处理已经接收的数据
        /// </summary>
        /// <param name="frames"></param>
        private void Msg_DataReceived(List<short[]> frames)
        {
            _audioQueue.Enqueue(frames);


        }
        private readonly ConcurrentQueue<List<short[]>> _audioQueue = new ConcurrentQueue<List<short[]>>();
        private readonly CancellationTokenSource _cts = new CancellationTokenSource();
        private Thread _processingThread;
        private void Msg_OnCompleted(ChannelMessage channelMessage)
        {
            base.BeginInvoke(new MessageCompletedEventHandler(this.OnCompleted), new object[]
            {
                channelMessage
            });
        }



        private void DataReceived(List<short[]> frames)
        {
            try
            {
                if (SystemSetting.isSaveDataToFile)
                {
                    if (this.hasWrittenPointCountToFile <= SystemSetting.maxPointCountOfFile && MainForm.IsToLog)
                    {
                        if (this.hasWrittenPointCountToFile >= 0)
                        {
                            goto IL_17B;
                        }
                    }
                    try
                    {
                        this.hasWrittenPointCountToFile = 0;
                        if (this.swOfSaveFile != null)
                        {
                            this.swOfSaveFile.Close();
                            this.swOfSaveFile.Dispose();
                            this.swOfSaveFile = null;
                        }
                        if (File.Exists(SystemSetting.DataSavedFileName))
                        {
                            File.Delete(this.getBackupFileNameOfSavedFile(SystemSetting.DataSavedFileName));
                            File.Move(SystemSetting.DataSavedFileName, this.getBackupFileNameOfSavedFile(SystemSetting.DataSavedFileName));


                        }
                        this.swOfSaveFile = new StreamWriter(SystemSetting.DataSavedFileName, false, Encoding.ASCII);
                        StringBuilder stringBuilder = new StringBuilder(128);
                        stringBuilder.Append(SystemSetting.SampleFrenquency.Value.ToString());
                        for (int i = 1; i < Program.CountChannel + 1; i++)
                        {
                            ChannelSeting channelSeting = SystemSetting.Channels[i];
                            if (channelSeting.Address.Value != 0)
                            {
                                stringBuilder.Append(string.Format(",{0}#{1}", channelSeting.Address.Value.ToString("X4"), channelSeting.SignalType.ToString()));
                            }
                        }
                        this.swOfSaveFile.WriteLine(stringBuilder.ToString()); //写入日志
                    }
                    catch (Exception exception)
                    {
                        //SystemSetting.isSaveDataToFile = false;
                        if (this.swOfSaveFile != null)
                        {
                            this.swOfSaveFile.Close();
                            this.swOfSaveFile.Dispose();
                            this.swOfSaveFile = null;
                        }
                        InternalLoggerFactory.Logger.Error(string.Format("open or create file: {0} failed", SystemSetting.DataSavedFileName), exception);
                    }
                }
            IL_17B:
                foreach (short[] array in frames)
                {
                    this.receivedFrameCount += 1UL;
                    int num = 0;
                    if (this.preFrameNo != null)
                    {
                        int num2 = (this.preFrameNo.Value + 1) % 256;
                        if (num2 != (int)array[0])
                        {
                            if (num2 < (int)array[0])
                            {
                                num = (int)array[0] - num2;
                            }
                            else
                            {
                                num = (int)(array[0] + 256) - num2;
                            }
                        }
                        this.preFrameNo = new int?((int)array[0]);
                    }
                    else
                    {
                        this.preFrameNo = new int?((int)array[0]);
                    }
                    this.paddingFrameCount += (ulong)((long)num);


                    //数据保存
                    if (SystemSetting.isSaveDataToFile && this.swOfSaveFile != null && channel != null && channel.IsConnected())
                    {


                        if (!File.Exists(SystemSetting.DataSavedFileName))
                        {
                            File.Create(SystemSetting.DataSavedFileName);
                        }
                        try
                        {
                            for (int j = 0; j < num; j++)
                            {
                                this.swOfSaveFile.WriteLine(this.GetSaveStr(array, true));
                                this.hasWrittenPointCountToFile++;
                            }
                            this.swOfSaveFile.WriteLine(this.GetSaveStr(array, false));
                            this.hasWrittenPointCountToFile++;
                        }
                        catch (Exception exception2)
                        {
                            //SystemSetting.isSaveDataToFile = false;
                            if (this.swOfSaveFile != null)
                            {
                                this.swOfSaveFile.Close();
                                this.swOfSaveFile.Dispose();
                                this.swOfSaveFile = null;
                            }
                            InternalLoggerFactory.Logger.Error(string.Format("write to file: {0} failed", SystemSetting.DataSavedFileName), exception2);
                        }
                    }
                    for (int k = 0; k < this.tempFrameData.Length; k++)
                    {
                        this.tempFrameData[k] = null;
                    }
                    for (int l = 0; l < num; l++)
                    {
                        this.oscilloscopeControl1.AddSampleData(this.tempFrameData);
                    }
                    for (int m = 1; m < array.Length; m++)
                    {
                        if (this.chMemoryBufs != null)
                        {
                            this.tempFrameData[this.chMemoryBufs[m - 1].ChSN - 1] = new short?(array[m]);
                        }
                    }
                    this.oscilloscopeControl1.AddSampleData(this.tempFrameData);
                }
            }
            catch (Exception exception3)
            {
                InternalLoggerFactory.Logger.Error("deal with receive frame data error.", exception3);
            }
        }

        /// <summary>
        /// 转换成字符转
        /// </summary>
        /// <param name="framedata"></param>
        /// <param name="isEmpty"></param>
        /// <returns></returns>
        private string GetSaveStr(short[] framedata, bool isEmpty)
        {
            StringBuilder stringBuilder = new StringBuilder();
            {
                List<string> strings = new List<string>();
                for (int i = 1; i < framedata.Length; i++)
                {
                    ENUM_Ratio eNUM_Ratio = SystemSetting.Channels[this.chMemoryBufs[i - 1].ChSN].WaveRatio;
                    double ra = 1.0;
                    switch (eNUM_Ratio)
                    {
                        case ENUM_Ratio.x1:
                            ra = 1.0;
                            break;
                        case ENUM_Ratio.x10:
                            ra = 10.0;
                            break;
                        case ENUM_Ratio.x100:
                            ra = 100.0;
                            break;
                        case ENUM_Ratio.x1k:
                            ra = 1000.0;
                            break;
                        case ENUM_Ratio.x10k:
                            ra = 10000.0;
                            break;
                        case ENUM_Ratio.x100k:
                            ra = 100000.0;
                            break;
                        default:
                            break;
                    }
                    if (SystemSetting.Channels[this.chMemoryBufs[i - 1].ChSN].SignalType == ENUM_001.I16 || SystemSetting.Channels[this.chMemoryBufs[i - 1].ChSN].SignalType == ENUM_001.F32)
                    {
                        //arg = framedata[i].ToString();//转换成有符号
                        var arg = (Convert.ToDouble(framedata[i]) / ra).ToString();//转换成有符号
                        strings.Add(arg.ToString());
                    }
                    else
                    {
                        //arg = ((ushort)framedata[i]).ToString();//转换成无符号
                        var arg = (Convert.ToDouble((ushort)framedata[i]) / ra).ToString();//转换成无符号
                        strings.Add(arg.ToString());
                    }

                }
                //Console.WriteLine(string.Join(",", strings));
                stringBuilder.Append(framedata[0] + ",");
                stringBuilder.Append(string.Join(",", strings));

            }
            //StringBuilder stringBuilder = new StringBuilder(128);
            //if (!isEmpty)
            //{
            //    for (int i = 0; i < framedata.Length; i++)
            //    {
            //        if (i == 0)
            //        {
            //            if (stringBuilder.Length > 0)
            //            {
            //                stringBuilder.Append(string.Format(",{0}", ((ushort)framedata[i]).ToString()));
            //            }
            //            else
            //            {
            //                stringBuilder.Append(string.Format("{0}", ((ushort)framedata[i]).ToString()));
            //            }
            //        }
            //        else
            //        {
            //            string arg;
            //            ENUM_Ratio eNUM_Ratio = SystemSetting.Channels[this.chMemoryBufs[i - 1].ChSN].WaveRatio;
            //            double ra = 1.0;
            //            switch (eNUM_Ratio)
            //            {
            //                case ENUM_Ratio.x10:
            //                    ra = 10.0;
            //                    break;
            //                case ENUM_Ratio.x100:
            //                    ra = 100.0;
            //                    break;
            //                case ENUM_Ratio.x1k:
            //                    ra = 1000.0;
            //                    break;
            //                case ENUM_Ratio.x10k:
            //                    ra = 10000.0;
            //                    break;
            //                case ENUM_Ratio.x100k:
            //                    ra = 100000.0;
            //                    break;
            //                default:
            //                    break;
            //            }

            //            if (SystemSetting.Channels[this.chMemoryBufs[i - 1].ChSN].SignalType == ENUM_001.I16 || SystemSetting.Channels[this.chMemoryBufs[i - 1].ChSN].SignalType == ENUM_001.F32)
            //            {
            //                //arg = framedata[i].ToString();//转换成有符号
            //                arg = (Convert.ToDouble(framedata[i]) / ra).ToString();//转换成有符号
            //            }
            //            else
            //            {
            //                //arg = ((ushort)framedata[i]).ToString();//转换成无符号
            //                arg = (Convert.ToDouble((ushort)framedata[i]) / ra).ToString();//转换成无符号
            //            }
            //            if (stringBuilder.Length > 0)
            //            {
            //                stringBuilder.Append(string.Format(",{0}", arg));
            //            }
            //            else
            //            {
            //                stringBuilder.Append(string.Format("{0}", arg));

            //            }
            //        }
            //    }
            //}
            //else
            //{
            //    for (int j = 0; j < framedata.Length - 1; j++)
            //    {
            //        stringBuilder.Append(",");
            //    }
            //}

            return stringBuilder.ToString();
        }

        // Token: 0x060000A6 RID: 166 RVA: 0x0000B3FC File Offset: 0x000095FC
        private void OnCompleted(ChannelMessage channelMessage)
        {
            Thread.Sleep(1000);
            this.toolStripStatusLabel.Text = string.Format("接收数据完成：总帧数={0} 填充帧数={1}", this.receivedFrameCount.ToString(), this.paddingFrameCount.ToString());
            this.channel.Close();
            while (!this.channel.IsClosed())
            {
                Thread.Sleep(500);
            }
            this.ctlMsg.OnCompleted -= this.Msg_OnCompleted;
            this.ctlMsg.DataReceived -= this.Msg_DataReceived;
            if (this.swOfSaveFile != null)
            {
                try
                {
                    this.swOfSaveFile.Close();
                    this.swOfSaveFile.Dispose();
                    this.swOfSaveFile = null;
                }
                catch
                {
                }
            }
            this.hasWrittenPointCountToFile = -1;
            if (this.chMemoryBufs != null)
            {
                this.chMemoryBufs.Clear();
                this.chMemoryBufs = null;
            }
            this.preFrameNo = null;
            this.receivedFrameCount = 0UL;
            this.paddingFrameCount = 0UL;
            this.runState = MainForm.RunState.Stoped;
            if (channelMessage.GetCause() != null)
            {
                MessageBox.Show("数据接收异常终止！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        private void StopSample()
        {
            if (this.runState == MainForm.RunState.Stoped)
            {
                return;
            }
            this.oscilloscopeControl1.StopRefresh();
            this.ctlMsg.Cancel();
        }

        private void ToolStripMenuItemUpdate_Click(object sender, EventArgs e)
        {
            if (this.runState == MainForm.RunState.Started)
            {
                return;
            }
            FlashUpdateForm flashUpdateForm = new FlashUpdateForm();
            flashUpdateForm.StartPosition = FormStartPosition.CenterParent;
            if (flashUpdateForm.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            dictionary.Add("baudRate", flashUpdateForm.Baudrate);
            dictionary.Add("dataBits", 8);
            dictionary.Add("stopBits", StopBits.One);
            dictionary.Add("parity", Parity.None);
            dictionary.Add("readTimeoutMillis", 100);
            dictionary.Add("writeTimeoutMillis", 100);
            dictionary.Add("readBufferSize", 1024);
            dictionary.Add("writeBufferSize", 1024);
            SerialAddress remoteAddress = new SerialAddress(flashUpdateForm.Port);
            SerialChannelFactory channelFactory = new SerialChannelFactory();
            ClientBootstrap clientBootstrap = new ClientBootstrap(channelFactory);
            clientBootstrap.SetOptions(dictionary);
            try
            {
                this.channel = clientBootstrap.connect(remoteAddress);
            }
            catch (Exception exception)
            {
                InternalLoggerFactory.Logger.Error("打开串口失败", exception);
                MessageBox.Show("打开串口失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return;
            }
            try
            {
                if (Enum.GetName(typeof(FlashUpdateType), flashUpdateForm.UpdateType).Contains("DSP"))
                {
                    Coffile coffile = null;
                    try
                    {
                        coffile = CoffParser.GetCoffile(flashUpdateForm.FirmwareFile);
                    }
                    catch (Exception exception2)
                    {
                        InternalLoggerFactory.Logger.Error("读取固件文件失败", exception2);
                    }
                    if (coffile == null)
                    {
                        MessageBox.Show("读取固件文件失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                    else
                    {
                        DspUpdateForm dspUpdateForm = new DspUpdateForm(this.channel, flashUpdateForm.UpdateType, flashUpdateForm.IsUpdateKernal, coffile);
                        dspUpdateForm.StartPosition = FormStartPosition.CenterParent;
                        dspUpdateForm.ShowDialog(this);
                        dspUpdateForm.Dispose();
                    }
                }
                else
                {
                    FpgaUpdateForm fpgaUpdateForm = new FpgaUpdateForm(this.channel, flashUpdateForm.UpdateType, flashUpdateForm.FirmwareFile);
                    fpgaUpdateForm.StartPosition = FormStartPosition.CenterParent;
                    fpgaUpdateForm.ShowDialog(this);
                    fpgaUpdateForm.Dispose();
                }
            }
            finally
            {
                try
                {
                    this.channel.Close();
                }
                catch (Exception exception3)
                {
                    InternalLoggerFactory.Logger.Error("关闭串口失败", exception3);
                    MessageBox.Show("关闭串口失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
        }

        // Token: 0x060000A9 RID: 169 RVA: 0x0000B7C8 File Offset: 0x000099C8
        private void ToolStripMenuItemSet_Click(object sender, EventArgs e)
        {
            if (this.runState == MainForm.RunState.Started)
            {
                return;
            }
            DspDataLoadForm dspDataLoadForm = new DspDataLoadForm();
            //dspDataLoadForm.ShowDialog();
            dspDataLoadForm.Dispose();
        }

        // Token: 0x060000AA RID: 170 RVA: 0x0000B7F4 File Offset: 0x000099F4
        private string getBackupFileNameOfSavedFile(string filePathName)
        {
            string extension = Path.GetExtension(filePathName);
            string fullPath = Path.GetFullPath(filePathName);
            return filePathName.Substring(0, fullPath.LastIndexOf(extension)) + "_backup" + extension;
        }

        // Token: 0x040000BC RID: 188
        private static int CHANNEL_COUNT = Program.CountChannel;

        // Token: 0x040000BD RID: 189
        private MainForm.RunState runState;

        // Token: 0x040000BE RID: 190
        public Channel channel;

        // Token: 0x040000BF RID: 191
        private ControlChannelMessage ctlMsg;

        // Token: 0x040000C0 RID: 192
        private StreamWriter swOfSaveFile;

        // Token: 0x040000C1 RID: 193
        private int hasWrittenPointCountToFile;

        // Token: 0x040000C2 RID: 194
        private List<MainForm.ChannelBufferMemory> chMemoryBufs;

        // Token: 0x040000C3 RID: 195
        private int? preFrameNo = null;

        // Token: 0x040000C4 RID: 196
        private ulong receivedFrameCount;

        // Token: 0x040000C5 RID: 197
        private ulong paddingFrameCount;

        // Token: 0x040000C6 RID: 198
        private short?[] tempFrameData = new short?[Program.CountChannel];

        // Token: 0x02000019 RID: 25
        private enum RunState
        {
            // Token: 0x040000DB RID: 219
            Stoped,
            // Token: 0x040000DC RID: 220
            Started
        }

        // Token: 0x0200001A RID: 26
        private class ChannelBufferMemory
        {
            // Token: 0x060000AE RID: 174 RVA: 0x0000C154 File Offset: 0x0000A354
            public ChannelBufferMemory(int channelSn, IChannelBuffer buffer)
            {
                this.ChSN = channelSn;
                this.buf = buffer;
            }

            // Token: 0x040000DD RID: 221
            public int ChSN;

            // Token: 0x040000DE RID: 222
            public IChannelBuffer buf;
        }
        public InitialData symbolModel = null;


        public static Func<bool, string, List<string>, InitialData> GetFileSymbolModel;

        private void oscilloscopeControl1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }

        }

        public static string filePathGlobal = string.Empty;



        private async void oscilloscopeControl1_DragDrop(object sender, DragEventArgs e)
        {
            string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            await ShowPath(path);

        }

        private async Task ShowPath(string path)
        {
            toolStripLabel2.ForeColor = Color.Black;
            toolStripLabel2.Text = $"当前加载文件为:{path},正在加载文件中...";
            await Task.Run(() =>
            {
                try
                {
                    OscilloscopeControl.ModelAppSettingsCustom.OutPathHistory = path;
                    DwarfHelper.DwarfHelperInstance.LoadFile(path);
                }
                catch (Exception)
                {
                    toolStripLabel2.Text = $"当前加载文件为:{path},加载文件失败!";
                    toolStripLabel2.ForeColor = Color.Red;
                }
            });
            toolStripLabel2.Text = $"当前加载文件为:{path},加载文件成功!";
            toolStripLabel2.ForeColor = Color.Blue;
        }

        public static Action<string> ChangeProperty;

        private async void toolStripButton_switchIPMOS_Click(object sender, EventArgs e)
        {
            try
            {
                string path = OscilloscopeControl.ModelAppSettingsCustom.OutPathHistory;
                if (!File.Exists(path))
                {
                    toolStripLabel2.Text = ("当前没有加载文件,请重新载入文件,刷新文件失败!");
                    toolStripLabel2.ForeColor = Color.Red;

                    return;
                }
                toolStripLabel2.ForeColor = Color.Black;
                toolStripLabel2.Text = $"当前加载文件为:{path},正在加载文件中...";
                await Task.Run(() =>
                  {
                      try
                      {
                          DwarfHelper.DwarfHelperInstance.LoadFile(OscilloscopeControl.ModelAppSettingsCustom.OutPathHistory);
                          OscilloscopeControl.ModelAppSettingsCustom.OutPathHistory = path;
                      }
                      catch (Exception)
                      {
                          toolStripLabel2.Text = $"当前加载文件为:{path},加载文件失败!";
                          toolStripLabel2.ForeColor = Color.Red;
                      }
                  });
                toolStripLabel2.Text = $"当前加载文件为:{path},加载文件成功!";
                toolStripLabel2.ForeColor = Color.Blue;
                OscilloscopeControl.BindingListmodelSaveStrings.ResetBindings();
                ChangeProperty?.Invoke(OscilloscopeControl.ModelAppSettingsCustom.OutPathHistory);
                if (OscilloscopeControl.BindingListmodelSaveStrings != null)
                {
                    foreach (var item in OscilloscopeControl.BindingListmodelSaveStrings)
                    {
                        if (!string.IsNullOrEmpty(item.Name))
                        {
                            VariableInfo variableInfo = new VariableInfo(item.Name, string.Empty);
                            DwarfHelper.DwarfHelperInstance.GetAddress(new List<VariableInfo>() { variableInfo });
                            if (!string.IsNullOrEmpty(variableInfo.Address))
                                item.Address = variableInfo.Address;
                            else
                            {
                                item.Address = "00000000";
                            }
                        }
                    }
                }
                string _dataFilePath = "configData.json";
                if (File.Exists(_dataFilePath))
                {
                    string jsonData = File.ReadAllText(_dataFilePath);
                    var _configs = JsonConvert.DeserializeObject<List<ItemConfig>>(jsonData);
                    foreach (var item in _configs)
                    {
                        if (!string.IsNullOrEmpty(item.ComboBoxItem))
                        {
                            VariableInfo variableInfo = new VariableInfo(item.ComboBoxItem, string.Empty);
                            DwarfHelper.DwarfHelperInstance.GetAddress(new List<VariableInfo>() { variableInfo });
                            if (!string.IsNullOrEmpty(variableInfo.Address))
                                item.AddressContent = variableInfo.Address;
                            else
                            {
                                item.AddressContent = "00000000";
                            }
                        }
                    }
                    string jsonDataAgain = JsonConvert.SerializeObject(_configs, Formatting.Indented);
                    File.WriteAllText(_dataFilePath, jsonDataAgain);
                }
                //  MessageBox.Show("刷新地址成功!");
            }
            catch (Exception)
            {
                MessageBox.Show("刷新地址失败!");
            }

            #region MyRegion
            //growatt.Message.Osc.SwitchIPMOS addrSetChannelMessage = new growatt.Message.Osc.SwitchIPMOS();//发送所有地址信息(地址设置)
            //addrSetChannelMessage.SetSendTimeoutMillis(1000);
            //addrSetChannelMessage.SetSpaceReceiveTimeoutMillis(1000);
            //addrSetChannelMessage.SetTotalReceiveTimeoutMillis(1000);
            //try
            //{
            //    if (this.channel != null)
            //    {
            //        this.channel.WriteAsync(addrSetChannelMessage);
            //        addrSetChannelMessage.AwaitUninterruptibly();
            //        if (!addrSetChannelMessage.IsSuccess())
            //        {

            //            throw new Exception("地址设置消息处理失败", addrSetChannelMessage.GetCause());
            //        }
            //        if (addrSetChannelMessage.ErrorCode != OscErrorCode.SUCCESS)
            //        {
            //            MessageBox.Show("地址设置消息处理失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);

            //            throw new Exception("地址设置消息处理失败", new Exception("消息错误码不是 SUCCESS"));
            //        }
            //    }
            //    else
            //    {
            //        MessageBox.Show("地址设置消息处理失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            //    }

            //}
            //catch (Exception exception2)
            //{
            //    this.channel.Close();
            //    while (!this.channel.IsClosed())
            //    {
            //        Thread.Sleep(500);
            //    }
            //    InternalLoggerFactory.Logger.Error(string.Format("write data [fun={0} errorcode={1}] error, sendmsg:{2}, receivemsg:{3}", new object[]
            //    {
            //        addrSetChannelMessage.Fun,
            //        addrSetChannelMessage.ErrorCode.ToString(),
            //        addrSetChannelMessage.HexDumpSendMessage(),
            //        addrSetChannelMessage.HexDumpReceiveMessage()
            //    }), exception2);
            //    MessageBox.Show("设置通道地址错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            //    return;
            //} 
            #endregion

        }
        /// <summary>
        /// 判断是否记录日志(默认开始记录数据)
        /// </summary>
        public static bool IsToLog = true;

        private void toolStripButton_InsertConfig_Click(object sender, EventArgs e)
        {
            #region MyRegion
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = true;
            openFileDialog.Title = "Select Files";
            openFileDialog.Filter = "ini files (*.ini)|*.ini";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string[] selectedFiles = openFileDialog.FileNames;
                foreach (string file in selectedFiles)
                {
                    Name = file.Split('\\')[file.Split('\\').Length - 1];
                    if (Name.Equals("ConfigSys.ini"))
                    {
                        string fileDatas = File.ReadAllText(openFileDialog.FileName);
                        //反序列化
                        var list = DuiJsonHelper.JsonToObject<List<ModelSaveString>>(fileDatas);
                        if (list != null)
                            OscilloscopeControl.modelSaveStrings = list;
                        else OscilloscopeControl.modelSaveStrings = new List<ModelSaveString>();
                    }
                    if (Name.Equals("ConfigChanelControlSys.ini"))
                    {
                        List<ConfigChannelControlModel> ConfigChanelControlSyslist = null;
                        {
                            string fileDatas = File.ReadAllText(openFileDialog.FileName);
                            ConfigChanelControlSyslist = DuiJsonHelper.JsonToObject<List<ConfigChannelControlModel>>(fileDatas);
                        }
                        if (ConfigChanelControlSyslist?.Count > 0 && ConfigChanelControlSyslist?.Count == OscilloscopeControl.listChnnel.Count)
                        {
                            for (int i = 0; i < ConfigChanelControlSyslist?.Count; i++)
                            {
                                var item = ConfigChanelControlSyslist[i];
                                OscilloscopeControl.listChnnel[i].LoadChannelControlConfig(item.ChannelSN, item.LineColor, item.LineWidth, item.SignalName, item.ValuePerCellGrade, item.VerPos, item.BitMask);
                            }
                        }
                        else
                        {
                            MessageBox.Show("当前导入的配置与当前的通道数量不一致!");
                        }

                    }

                    if (Name.Equals("ModelSaveChaneltempLoad.ini"))
                    {
                        string fileDatas = File.ReadAllText(openFileDialog.FileName);
                        OscilloscopeControl.ModelSaveChanelLoadsFiles = DuiJsonHelper.JsonToObject<ModelSaveChaneltempLoad>(fileDatas);
                    }
                }
            }
            #endregion




        }




        /// <summary>
        /// 导出配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            //string path = Path.Combine($"{Environment.CurrentDirectory}\\Parser", $"ConfigSys.ini"); //获取当前路径
            //string path2 = Path.Combine($"{Environment.CurrentDirectory}\\Parser", $"ConfigChanelControlSys.ini"); //获取当前路径
            //CloseToSaving();
            //File.Copy(path, Path.Combine($"{System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}", $"ConfigSys.ini"), true); //将文件拷贝到桌面
            //File.Copy(path2, Path.Combine($"{System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}", $"ConfigChanelControlSys.ini"), true); //将文件拷贝到桌面
            //MessageBox.Show("导出文件成功!");
            // 调用OscilloscopeScreen.SaveValue方法保存文件
            // 定义源文件路径和目标路径
            if (!Directory.Exists(Path.Combine(Environment.CurrentDirectory, "FileLog")))
                Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, "FileLog"));
            string destinationPath = Path.Combine($"{Environment.CurrentDirectory}\\FileLog", $"{System.DateTime.Now.ToString("yyyyMMddHHmmss")}_FileLog.csv");
            OscilloscopeScreen.SaveValue?.Invoke(destinationPath);
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(Path.Combine(Environment.CurrentDirectory, "FileLog")))
                Directory.CreateDirectory(Path.Combine(Environment.CurrentDirectory, "FileLog"));
            string directoryPath = Path.Combine(Environment.CurrentDirectory, "FileLog"); // 打开的目录路径
            try
            {
                Process.Start("explorer.exe", directoryPath);
            }
            catch (Exception ex)
            {
                Console.WriteLine("打开目录时发生错误: " + ex.Message);
            }
        }
    }
}
